import { TreeSelect } from 'antd';
import React, { useState, useEffect } from 'react';
import { categoryAll } from '../../services/common';

interface BaseProps {
  placeholder?: string
}
interface stateData {
  list: Array<any>,
}

const UploadFile: React.FC<BaseProps> = (props) => {
  const [state, setState] = useState<stateData>({
    list: []
  });

  const recursionData = (data = [], pid = 0) => {
    const result: Array<any> = [];
    Array.isArray(data) && data.forEach((item: any, index) => {
      if (item.parent_id === pid) {
        const param = {
          title: item.name,
          value: item.id,
          key: `${pid}-${index}`,
          children: recursionData(data, item.id)
        };
        result.push(param);
      }
    });
    return result;
  };

  // 请求分类
  useEffect(() => {
    categoryAll().then(({ data }) => {
      const list = recursionData(data, 0)
      console.log(list)
      setState({ list })
    });
  }, []);

  const { list } = state;
  return (
    <TreeSelect
      {...props}
      treeData={list}
    />
  );
};

export default UploadFile;
